#!/usr/bin/python3
#coding:utf-8
__author__ 'merci'
from queue import Queue
from threading import Thread
import pymysql
import time
q = Queue()

def get_conn():
    conn = False
    try:
        conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='sulao', charset='utf8')
    except:
        print("Connect MySQL failed !")
        conn = False
    return conn

def get_data(sql):
    cur = get_conn().cursor()
    cur.execute(sql)
    data = cur.fetchall()
    return data

def add_queue(data):
    for p in data:
        q.put(p)
    return q

def build_file(_queue):
    while _queue.qsize() > 0:
    try:
        task = _queue.get()
        with open("html/%s.html" % task[0], 'w', encoding='utf-8') as f:
            html = """
                <html>
                <meta charset='utf-8' />
                <title>%s</title>
                <body>
                %s
                </body>
                </html>
            """ % (task[1], task[2])
            f.write(html)
        _queue.task_done()
    except:
        print("%s , Write failed !" % task[1])

if __name__ == "__main__":
    start_time = time.time()
    sql = """SELECT `log_ID`,`log_Title`,`log_Content` FROM `zbp_post` WHERE `log_Status`=0 ORDER BY `log_ID` ASC"""
    data = get_data(sql)
    print("总共 %d 条数据" % len(data))
    _queue = add_queue(data)
    threads = []
    for k in range(4):
        t = Thread(target=build_file, args=(_queue,))
        threads.append(t)
    for ts in threads:
        ts.start()
        ts.join()
    _queue.join()
    end_time = time.time()
    print("耗时 %.3f " % (end_time - start_time))